<template>
	<cl-dialog
		title="管理权限组"
		width="650px"
		:visible.sync="visible"
		:before-close="beforeClose"
		@close="close"
		:props="{
			top: '10vh'
		}"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-form-item label="管理权限组" prop="is_assign" required>
				<el-radio-group v-model="form.is_assign">
					<el-radio :label="0">全部</el-radio>
					<el-radio :label="1">指定</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="指定权限组" prop="manage_role_ids" v-if="form.is_assign == 1">
				<el-checkbox-group v-model="form.manage_role_ids">
					<el-row>
						<el-col :span="8" v-for="(item, index) in roleList" :key="index">
							<el-checkbox :label="item.ro_id" name="manage_role_ids">
								{{ item.ro_name }}
							</el-checkbox>
						</el-col>
					</el-row>
				</el-checkbox-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="close">关闭</el-button>
			<el-button type="primary" @click="submit" :loading="saving">确定</el-button>
		</template>
	</cl-dialog>
</template>
<script>
export default {
	name: "manage-channel",
	data() {
		return {
			visible: false,
			form: {
				ro_id: "",
				is_assign: 0, // 是否指定
				manage_role_ids: [],
				manage_role_id: ""
			},
			rules: {
				manage_role_ids: [{ required: true, message: "请选择权限组" }]
			},
			saving: false,
			roleList: []
		};
	},
	methods: {
		open({ ro_id, manage_role_id, biz_id }) {
			this.visible = true;
			let is_assign = manage_role_id == "*" ? 0 : 1;
			this.form.is_assign = is_assign;
			this.form.ro_id = ro_id;
			this.form.manage_role_ids =
				is_assign == 0 ? [] : (manage_role_id || "").split(",").map(Number);
			this.form = {
				is_assign,
				ro_id,
				manage_role_id,
				manage_role_ids: is_assign == 0 ? [] : (manage_role_id || "").split(",").map(Number)
			};
			this.getRoleList(biz_id);
		},
		beforeClose(done) {
			if (this.saving) return;
			done();
		},
		close() {
			if (this.saving) return;
			this.visible = false;
			this.reset();
		},
		reset() {
			this.saving = false;
			this.$refs.form.resetFields();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				try {
					this.saving = true;
					const { is_assign, ro_id, manage_role_ids } = this.form;
					let form = {
						ro_id,
						manage_role_id: is_assign ? manage_role_ids.join() : "*"
					};
					await this.$service.role.manageRole(form);
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.saving = false;
					this.close();
				} catch (error) {
					this.saving = false;
				}
			});
		},
		// 角色
		async getRoleList(biz_id) {
			this.roleList = [];
			const data = await this.$service.role.list({ biz_id });
			this.roleList = data;
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-dialog__body {
		max-height: 70vh;
		overflow: auto;
	}
}
</style>
